package com.dom.stor.modular.provider;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dom.api.stor.StorStockinApi;
import com.dom.api.stor.StorStockoutApi;
import com.dom.common.constants.ConstantError;
import com.dom.common.enums.PubStatEnum;
import com.dom.common.exception.ServiceException;
import com.dom.common.model.vo.stor.*;
import com.dom.common.utils.BeanUtil;
import com.dom.stor.dao.entity.*;
import com.dom.stor.dao.service.*;
import com.dom.stor.modular.service.StockinService;
import com.xiaoleilu.hutool.collection.CollectionUtil;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description 出库单服务者
 * @Author xllei
 * @Date 2018/12/21 2:52 PM
 * @Version 1.0
 **/
@Slf4j
@RestController
public class StockoutProvider implements StorStockoutApi {
    @Autowired
    private ITsStockOutFlowService stockOutFlowService;
    @Autowired
    private ITsStockOutDetailFlowService stockOutDetailFlowService;
    @Autowired
    private ITTradeDateService tradeDateService;
    @Autowired
    private ITGoodsInfoService goodsInfoService;
    @Autowired
    private ITGoodStandardTblService goodStandardTblService;
    @Autowired
    private ITGoodVarietyTblService goodVarietyTblService;
    @Autowired
    private ITMeasureUnitTblService measureUnitTblService;
    @Autowired
    private ITStorInfoService storInfoService;
    @Autowired
    private ITOrganInfoService organInfoService;
    @Autowired
    private ITUserInfoService userInfoService;

    @Override
    public S039A findStockoutPager(@RequestBody S039R request) {
        Page<TsStockOutFlow> pager = new Page<>();
        Wrapper<TsStockOutFlow> wrapper = new EntityWrapper<>();
        wrapper.eq("mem_code", request.getMemCode());

        //赋值分页信息
        pager.setCurrent(request.getPn());
        pager.setSize(request.getPs() != 0 ? request.getPs() : 20);

        //赋值查询条件
        wrapper.eq("mem_code", request.getMemCode());
        if (ObjectUtil.isNotNull(request.getStockDate())) {
            wrapper.and().eq("stock_date", request.getStockDate());
        }
        if (ObjectUtil.isNotNull(request.getStockType())) {
            wrapper.and().eq("stock_type", request.getStockType());
        }
        if(ObjectUtil.isNotNull(request.getStorCode())){
            wrapper.and().eq("stor_code", request.getStorCode());
        }
        if(ObjectUtil.isNotNull(request.getOrganCode())){
            wrapper.and().eq("organ_code", request.getOrganCode());
        }
        if(ObjectUtil.isNotNull(request.getStat())){
            wrapper.and().eq("stat", request.getStat());
        }
        if(ObjectUtil.isNotNull(request.getVerfyStat())){
            wrapper.and().eq("verfy_stat", request.getVerfyStat());
        }

        pager = stockOutFlowService.selectPage(pager, wrapper);
        List<StockoutInfo> records = convert2Pojo(pager.getRecords(), request.getMemCode());

        S039A response = new S039A();
        response.setTotalNum((int) pager.getTotal());

        response.setStockoutInfos(records);
        return response;
    }

    private List<StockoutInfo> convert2Pojo(List<TsStockOutFlow> entities, Integer memCode){
        //赋值仓库、机构名称
        Map<Integer, String> storNameList = storInfoService.getStorNameList(memCode);
        Map<Integer, String> organNameList = organInfoService.getOrganNameList(memCode);
        Map<Integer, String> userNameList = userInfoService.getUserNameList(memCode);

        List<StockoutInfo> stockoutInfos = new ArrayList<>();
        entities.forEach(entity->{
            StockoutInfo stockoutInfo = new StockoutInfo();
            BeanUtil.copyPropertiesIgnoreNull(entity,stockoutInfo);
            stockoutInfo.setStockId(entity.getId());
            stockoutInfo.setStockDate(DateUtil.format(entity.getStockDate(), "yyyy-MM-dd"));
            stockoutInfo.setMakeDate(DateUtil.format(entity.getMakeDate(), "yyyy-MM-dd HH:mm:ss"));
            stockoutInfo.setExchDate(DateUtil.format(entity.getExchDate(), "yyyy-MM-dd"));
            stockoutInfo.setVerfyDate(DateUtil.format(entity.getVerfyDate(), "yyyy-MM-dd HH:mm:ss"));
            stockoutInfo.setMakerId(entity.getDocuMakerId());

            stockoutInfo.setStorName(storNameList.get(entity.getStorCode()));
            stockoutInfo.setOrganName(organNameList.get(entity.getOrganCode()));
            stockoutInfo.setMakerName(userNameList.get(entity.getDocuMakerId()));

            stockoutInfos.add(stockoutInfo);
        });
        return stockoutInfos;
    }

    @Override
    public S030A addStockoutBill(@RequestBody S030R request) {
        TsStockOutFlow stockOutFlow = new TsStockOutFlow();
        BeanUtil.copyPropertiesIgnoreNull(request, stockOutFlow);
        stockOutFlow.setStockDate(DateUtil.parse(request.getStockDate(), "yyyy-MM-dd"));
        stockOutFlow.setOrganCode(request.getOrgId());
        stockOutFlow.setDocuMakerId(request.getOperId());
        stockOutFlow.setMakeDate(new Date());
        stockOutFlow.setExchDate(tradeDateService.getExchDate(request.getMemCode()));
        stockOutFlow.setStat(PubStatEnum.STAT_NORMAL.getCode());
        stockOutFlow.setVerfyStat(PubStatEnum.STAT_NORMAL.getCode());
        stockOutFlow.setCancelStat(PubStatEnum.STAT_NORMAL.getCode());

        boolean result = stockOutFlowService.insert(stockOutFlow);
        if(!result){
            log.warn("录入入库单异常", result);
            throw new ServiceException(ConstantError.DATAERROR);
        }

        //批量录入入库单明细
        addStockoutDetail(request, stockOutFlow);

        S030A response = new S030A();
        response.setStockId(stockOutFlow.getId());
        return response;
    }

    /**
     * 增加出库单明细
     * @param request
     * @param stockOutFlow
     * @return
     */
    private boolean addStockoutDetail(S030R request, TsStockOutFlow stockOutFlow) {
        //获取商品信息
        Map<Integer, TGoodsInfo> goodsList = goodsInfoService.getGoodInfoList(request.getMemCode());
        Map<Integer, String> standardNameList = goodStandardTblService.getStandardNameList(request.getMemCode());
        Map<Integer, String> varietyNameList = goodVarietyTblService.getVarietyNameList(request.getMemCode());
        Map<Integer, String> unitList = measureUnitTblService.getUnitList(request.getMemCode());


        List<TsStockOutDetailFlow> stockOutDetailFlows = new ArrayList<>();
        request.getStockDetailInfos().forEach(detailItem ->{
            TsStockOutDetailFlow stockOutDetailFlow = new TsStockOutDetailFlow();
            BeanUtil.copyPropertiesIgnoreNull(detailItem, stockOutDetailFlow);
            stockOutDetailFlow.setMemCode(request.getMemCode());
            stockOutDetailFlow.setStat(PubStatEnum.STAT_NORMAL.getCode());
            stockOutDetailFlow.setStockId(stockOutFlow.getId().toString());

            //赋值商品信息
            TGoodsInfo goodInfo = goodsList.get(detailItem.getGoodCode());
            stockOutDetailFlow.setGoodName(goodInfo.getGoodName());
            stockOutDetailFlow.setVarietyCode(goodInfo.getVarietyCode());
            stockOutDetailFlow.setVarietyName(varietyNameList.get(goodInfo.getVarietyCode()));
            stockOutDetailFlow.setStandardName(standardNameList.get(goodInfo.getStandardCode()));
            stockOutDetailFlow.setUnit(unitList.get(goodInfo.getUnitCode()));
            stockOutDetailFlows.add(stockOutDetailFlow);
        });
        boolean result = stockOutDetailFlowService.insertBatch(stockOutDetailFlows);
        if(!result){
            log.info("批量录入入库单明细失败", result);
            throw new ServiceException(ConstantError.DATAERROR);
        }
        return result;
    }

    @Override
    public S049A findStockoutDetailList(@RequestBody S049R request) {
        Wrapper<TsStockOutDetailFlow> wrapper = new EntityWrapper<>();
        wrapper.eq("mem_code", request.getMemCode())
                .and().eq("stock_id", request.getStockId())
                .and().eq("stat", PubStatEnum.STAT_NORMAL.getCode())
                .orderBy("id");

        List<TsStockOutDetailFlow> stockInDetailFlows = stockOutDetailFlowService.selectList(wrapper);

        List<StockDetailInfo> stockDetailInfos = new ArrayList<>();
        stockInDetailFlows.forEach(entity -> {
            StockDetailInfo stockInDetailFlow = new StockDetailInfo();

            BeanUtil.copyPropertiesIgnoreNull(entity, stockInDetailFlow);

            stockDetailInfos.add(stockInDetailFlow);;
        });

        S049A response = new S049A();
        response.setTotalNum(stockInDetailFlows.size());
        response.setStockDetailData(stockDetailInfos);
        return response;
    }

    @Override
    public S032A editStockoutBill(@RequestBody S032R request) {
        //更新出库单信息
        TsStockOutFlow stockOutFlow = stockOutFlowService.selectById(request.getStockId());

        stockOutFlow.setStockDate(DateUtil.parse(request.getStockDate(), "yyyy-MM-dd"));
        stockOutFlow.setStockType(request.getStockType());
        stockOutFlow.setStorCode(request.getStorCode());
        stockOutFlow.setDigest(request.getDigest());
        stockOutFlow.setSourBillType(request.getSourBillType());
        stockOutFlow.setSourBillId(request.getSourBillId());
        stockOutFlow.setMtime(new Date());
        boolean result = stockOutFlowService.updateById(stockOutFlow);

        //更新入库单明细
        Wrapper<TsStockOutDetailFlow> wrapper = new EntityWrapper<>();
        wrapper.eq("mem_code", request.getMemCode())
                .and().eq("stock_id", request.getStockId())
                .and().eq("stat", PubStatEnum.STAT_NORMAL.getCode());
        List<TsStockOutDetailFlow> stockInDetailFlows = stockOutDetailFlowService.selectList(wrapper);
        stockInDetailFlows.forEach(entity -> {
            entity.setStat(PubStatEnum.STAT_STOP.getCode());
            entity.setMtime(new Date());
        });

        if(CollectionUtil.isNotEmpty(stockInDetailFlows)){
            stockOutDetailFlowService.updateBatchById(stockInDetailFlows);
        }

        //新增入库单明细
        List<TsStockOutDetailFlow> stockInDetailFlowList = convert2EntityList(request.getStockDetailInfos(), stockOutFlow);
        boolean detailResult = stockOutDetailFlowService.insertBatch(stockInDetailFlowList);
        S032A response = new S032A();
        response.setStockId(stockOutFlow.getId());
        return response;
    }

    private List<TsStockOutDetailFlow> convert2EntityList(List<StockDetailInfo> stockDetailInfos, TsStockOutFlow stockOutFlow){
        Map<Integer, String> goodNameList = goodsInfoService.getGoodNameList(stockOutFlow.getMemCode());
        List<TsStockOutDetailFlow> stockOutDetailFlows = new ArrayList<>();
        stockDetailInfos.forEach(stockDetailInfo -> {
            TsStockOutDetailFlow entity = new TsStockOutDetailFlow();
            BeanUtil.copyPropertiesIgnoreNull(stockDetailInfo, entity);
            entity.setMemCode(stockOutFlow.getMemCode());
            entity.setGoodName(goodNameList.get(stockDetailInfo.getGoodCode()));
            entity.setStockId(stockOutFlow.getId().toString());

            stockOutDetailFlows.add(entity);
        });

        return stockOutDetailFlows;
    }

    @Override
    public S031A delStockoutBill(@RequestBody S031R request) {
        TsStockOutFlow stockOutFlow = stockOutFlowService.selectById(request.getStockId());
        stockOutFlow.setStat(PubStatEnum.STAT_STOP.getCode());

        boolean result = stockOutFlowService.updateById(stockOutFlow);
        S031A response = new S031A();
        response.setStockId(stockOutFlow.getId());
        return response;
    }
}
